from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from nt import rename

from .forms import ArticleColumnForm, ArticlePostForm
from .models import ArticleColumn, ArticlePost


@login_required(login_url="/account/login")
@csrf_exempt  # 解决CSRF问题的一种方式
def article_column(request):
    """文章栏目视图"""
    if request.method == "GET":
        columns = ArticleColumn.objects.filter(user=request.user)
        column_form = ArticleColumnForm()
        return render(
            request,
            "article/column/article_column.html",
            {"columns": columns, "column_form": column_form})
    if request.method == "POST":
        column_name = request.POST["column"]  # 获取提交的栏目名称
        columns = ArticleColumn.objects.filter(  # 当前用户是否已有该栏目名称
            user_id=request.user.id, column=column_name)
        if columns:
            return HttpResponse("2")  # 2表示重名
        else:
            ArticleColumn.objects.create(user=request.user, column=column_name)
            return HttpResponse("1")  # 1表示允许创建


@login_required(login_url="/account/login")
@require_POST  # 只接收POST方式的提交
@csrf_exempt
def rename_article_column(request):
    """重命名文章栏目视图"""
    column_name = request.POST["column_name"]
    column_id = request.POST["column_id"]
    try:
        line = ArticleColumn.objects.get(id=column_id)  # 查询数据并重新赋值
        line.column = column_name
        line.save()
        return HttpResponse("1")
    except:
        return HttpResponse("0")


@login_required(login_url="/account/login")
@require_POST
@csrf_exempt
def del_article_column(request):
    """删除文章栏目视图"""
    column_id = request.POST["column_id"]
    try:
        line = ArticleColumn.objects.get(id=column_id)
        line.delete()
        return HttpResponse("1")
    except:
        return HttpResponse("2")


@login_required(login_url="/account/login")
@csrf_exempt
def article_post(request):
    if request.method == "POST":
        article_post_form = ArticlePostForm(data=request.POST)
        if article_post_form.is_valid():
            cd = article_post_form.cleaned_data
            try:
                new_article = article_post_form.save(commit=False)
                new_article.author = request.user
                new_article.column = request.user.article_column.get(id=request.POST['column_id'])
                new_article.save()
                return HttpResponse("1")
            except:
                return HttpResponse("2")
        else:
            return HttpResponse("3")
    else:
        article_post_form = ArticlePostForm()
        article_columns = request.user.article_column.all()  # 用户的栏目对象，ArticleColumn.object.filter(user=request.user也可)
        return render(request, "article/column/article_post.html",
            {"article_post_form": article_post_form, "article_columns": article_columns})


@login_required(login_url="/account/login")
def article_list(request):
    articles = ArticlePost.objects.filter(author=request.user)
    paginator = Paginator(articles, 10)  # 每个分页的文章数
    page = request.GET.get('page')
    try:
        current_page = paginator.page(page)
        current_list = current_page.object_list
    except PageNotAnInteger:
        current_page = paginator.page(1)
        current_list = current_page.object_list
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
        current_list = current_page.object_list 
    return render(request, "article/column/article_list.html", {"articles": current_list, "page": current_page})


@login_required(login_url="/account/login")
def article_detail(request, id, slug):
    article = get_object_or_404(ArticlePost, id=id, slug=slug)
    return render(request, "article/column/article_detail.html", {"article": article})


@login_required(login_url="/account/login")
@require_POST
@csrf_exempt
def del_article(request):
    article_id = request.POST['article_id']
    try:
        article = ArticlePost.objects.get(id=article_id)
        article.delete()
        return HttpResponse("1")
    except:
        return HttpResponse("2")


@login_required(login_url="/account/login")
@csrf_exempt
def edit_article(request, id, slug):
    if request.method == "GET":
        article_columns = request.user.article_column.all()
        article = get_object_or_404(ArticlePost, id=id, slug=slug)  # 只用id似乎不能获取
        this_article_form = ArticlePostForm(initial={"title": article.title})
        this_article_column = article.column
        return render(request, "article/column/edit_article.html", {
            "article": article, "article_columns": article_columns,
            "this_article_column": this_article_column, "this_article_form": this_article_form})
    else:
        redit_article = ArticlePost.objects.get(id=id, slug=slug)
        try:
            redit_article.column = request.user.article_column.get(id=request.POST['column_id']) 
            redit_article.title = request.POST['title']
            redit_article.body = request.POST['body'] 
            redit_article.save()
            return HttpResponse("1")
        except:
            return HttpResponse("2")
